package com.yungu.swift.order.utils;

import com.yungu.swift.utils.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class PayUrlBuilder {

    /**
     * RSA签名方式
     *
     * @param map
     * @param needWrapValue
     * @return
     */
    public static String buildUrl(Map<String, String> map, boolean needWrapValue) {
        StringBuilder sb = new StringBuilder();
        List<String> keyList = new ArrayList<String>(map.keySet());
        Collections.sort(keyList);
        for (int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            String value = map.get(key);
            if (needWrapValue) {
                sb.append(i == 0 ? "" : "&").append(key).append("=\"").append(value).append("\"");
            } else {
                if (StringUtils.isNotEmpty(value)) {
                    sb.append(i == 0 ? "" : "&").append(key).append("=").append(value);
                }
            }
        }
        return sb.toString();
    }

    /**
     * RSA2签名方式
     *
     * @param map
     * @param needWrapValue
     * @param isEncode
     * @param isSort
     * @return
     */
    public static String buildUrl(Map<String, String> map, boolean needWrapValue, boolean isEncode, boolean isSort) {
        StringBuilder sb = new StringBuilder();
        List<String> keyList = new ArrayList<String>(map.keySet());
        if (isSort) {
            Collections.sort(keyList);
        }
        for (int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            String value = map.get(key);
            if (isEncode) {
                try {
                    value = URLEncoder.encode(value, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            if (needWrapValue) {
                sb.append(i == 0 ? "" : "&").append(key).append("=\"").append(value).append("\"");
            } else {
                if (StringUtils.isNotEmpty(value)) {
                    sb.append(i == 0 ? "" : "&").append(key).append("=").append(value);
                }
            }
        }
        return sb.toString();
    }

}
